package com.atguigu.gmall.product.service;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class ManagerServiceImpl implements ManagerService {
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;
    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitService rabbitService;

    //获取一级分类的集合
    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    //获取二级分类的集合
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        QueryWrapper<BaseCategory2> wrapper = new QueryWrapper<>();
        wrapper.eq("category1_id", category1Id);
        return baseCategory2Mapper.selectList(wrapper);
    }

    //获取三级分类的集合
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        QueryWrapper<BaseCategory3> wrapper = new QueryWrapper<>();
        wrapper.eq("category2_id", category2Id);
        return baseCategory3Mapper.selectList(wrapper);
    }

    //根据分类id获取平台属性
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.attrInfoList(category1Id, category2Id, category3Id);
    }

    //添加或修改平台属性
    @Override
    @Transactional
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //TODO 单独添加平台属性时校验是否重复添加BaseAttrInfo 需要比较除id之外的所有属性
        //平台属性表BaseAttrInfo
        if (baseAttrInfo.getId() != null) {
            baseAttrInfoMapper.updateById(baseAttrInfo);
        } else {
            baseAttrInfoMapper.insert(baseAttrInfo);
        }
        //先把平台属性值表相关的全部删除 再添加
        QueryWrapper queryWrapper = new QueryWrapper<BaseAttrValue>();
        queryWrapper.eq("attr_id", baseAttrInfo.getId());
        baseAttrValueMapper.delete(queryWrapper);

        //平台属性值表BaseAttrValue  n
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if (!CollectionUtils.isEmpty(attrValueList)) {
            attrValueList.forEach(attrValue -> {
                //设置外键
                attrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(attrValue);
            });
        }
    }

    //根据平台属性ID获取平台属性
    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_id", attrId);
        return baseAttrValueMapper.selectList(wrapper);
    }

    //获取品牌分页列表
    @Override
    public IPage<BaseTrademark> selectPageBaseTrademark(Integer page, Integer limit) {
        return baseTrademarkMapper.selectPage(new Page<>(page, limit), null);
    }

    //删除品牌
    @Override
    public void remove(Long id) {
        baseTrademarkMapper.deleteById(id);
    }

    //添加品牌
    @Override
    public void save(BaseTrademark baseTrademark) {
        baseTrademarkMapper.insert(baseTrademark);
    }

    //根据id获取品牌
    @Override
    public BaseTrademark get(Long id) {
        return baseTrademarkMapper.selectById(id);
    }

    //修改品牌
    @Override
    public void update(BaseTrademark baseTrademark) {
        baseTrademarkMapper.updateById(baseTrademark);
    }

    //查询商品分页 根据三级分类id查
    @Override
    public IPage spuPage(Integer page, Integer limit, Long category3Id) {
        return spuInfoMapper.selectPage(new Page<SpuInfo>(page, limit), new QueryWrapper<SpuInfo>().eq("category3_id", category3Id));
    }

    //获取品牌(平台)属性
    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }

    //获取销售属性
    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    //添加spu
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        spuInfoMapper.insert(spuInfo);
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)) {
            spuImageList.forEach(spuImage -> {
                //设置外键
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            });
        }
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)) {
            spuSaleAttrList.forEach(spuSaleAttr -> {
                //设置外键
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)) {
                    spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                        //设置
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        //设置外键
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });
                }
            });
        }
    }

    //为了添加SKU 查询spu_image表中spuId对应的所有图片
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id", spuId));
    }

    //为了添加SKU 查询spuId对应的销售属性和属性值集合
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.spuSaleAttrList(spuId);
    }

    //添加SKU
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //保存 sku_info
        skuInfoMapper.insert(skuInfo);
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (!CollectionUtils.isEmpty(skuImageList)) {
            skuImageList.forEach(skuImage -> {
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            });
        }
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)) {
            skuAttrValueList.forEach(skuAttrValue -> {
                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            });
        }
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if (!CollectionUtils.isEmpty(skuSaleAttrValueList)) {
            skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            });
        }
    }

    //分页查询SKU
    @Override
    public IPage skuPage(Integer page, Integer limit) {
        return skuInfoMapper.selectPage(new Page<SkuInfo>(page, limit), null);
    }

    //上架
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.ONSALE);
        skuInfoMapper.updateById(skuInfo);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS, MqConst.ROUTING_GOODS_UPPER, skuId);
    }

    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.NOSALE);
        skuInfoMapper.updateById(skuInfo);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS, MqConst.ROUTING_GOODS_LOWER, skuId);

    }

    //Redisson解决缓存击穿问题
    @Autowired
    private RedissonClient redissonClient;

    public SkuInfo getSkuInfo(Long skuId) {
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;//Rediskey的规范
        String cacheKeyLock = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;//RedisLock的规范
        //1.查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        //2.若没有缓存 则查询数据库
        if (null == skuInfo) {
            //为避免缓存击穿 需要上锁
            RLock lock = redissonClient.getLock(cacheKeyLock);//创建锁
            try {
                // 参数: 尝试多久获取锁 锁的持有时间  共用时间单位
                Boolean isLock = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                //上锁成功 获取到了分布式锁
                if (isLock) {
                    try {
                        skuInfo = skuInfoMapper.selectById(skuId);
                        if (null != skuInfo) {
                            skuInfo.setSkuImageList(skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId)));
                            //3.将结果添加到缓存
                            redisTemplate.opsForValue().set(cacheKey, skuInfo,
                                    //为避免缓存雪崩 原有的失效时间基础上增加一个随机值
                                    RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300),
                                    TimeUnit.SECONDS);
                        } else {
                            //如果数据库也没有 为避免缓存穿透
                            skuInfo = new SkuInfo();//空结果 空对象
                            redisTemplate.opsForValue().set(cacheKey, skuInfo, 5, TimeUnit.MINUTES);
                        }
                    } finally {
                        //原子性解锁 Redisson封装了LUA脚本
                        lock.unlock();
                    }
                } else {
                    //未获取到分布式锁
                    try {
                        //等一会再取缓存 看看有没有数据
                        TimeUnit.SECONDS.sleep(3);
                        return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return skuInfo;
    }

//    分布式锁解决缓存击穿问题
//    @Override
//    public SkuInfo getSkuInfo(Long skuId) {
//        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;//Rediskey的规范
//        String cacheKeyLock = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;//RedisLock的规范
//        //1.查询缓存
//        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
//        //2.若没有缓存 则查询数据库
//        if (null == skuInfo) {
//            //为避免缓存击穿 上锁 分布式锁
//            String uuid = UUID.randomUUID().toString();
//            Boolean isLock = redisTemplate.opsForValue().setIfAbsent(cacheKeyLock, uuid,
//                    RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
//            //上锁成功 获取到了分布式锁
//            if (isLock) {
//                try {
//                    skuInfo = skuInfoMapper.selectById(skuId);
//                    if (null != skuInfo) {
//                        skuInfo.setSkuImageList(skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId)));
//                        //3.将结果添加到缓存
//                        redisTemplate.opsForValue().set(cacheKey, skuInfo,
//                                //为避免缓存雪崩 原有的失效时间基础上增加一个随机值
//                                RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300),
//                                TimeUnit.SECONDS);
//                    } else {
//                        //如果数据库也没有 为避免缓存穿透
//                        skuInfo = new SkuInfo();//空结果 空对象
//                        redisTemplate.opsForValue().set(cacheKey, skuInfo, 5, TimeUnit.MINUTES);
//                    }
//                } finally {
//                    //原子性解锁
//                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
//                    this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(cacheKeyLock), uuid);
//                }
//            } else {
//                //未获取到分布式锁
//                try {
//                    //等一会再取缓存 看看有没有数据
//                    TimeUnit.SECONDS.sleep(3);
//                    return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return skuInfo;
//    }

//1: 根据skuId查询库存表sku_info  通过主键   同时查询图片
//    //本地锁方式解决缓存击穿问题
//private final Lock lock = new ReentrantLock();//公平锁 等待时间越长获取锁的几率越大
//    @Override
//    public SkuInfo getSkuInfo(Long skuId) {
//        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;//Rediskey的规范 避免重名
//        //1.查询缓存
//        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
//        //2.若没有缓存 则查询数据库
//        if (null == skuInfo) {
//            //为避免缓存击穿 上锁
//            try {
//                //如果1s内获取锁 则返回true
//                boolean tryLock = lock.tryLock(1, TimeUnit.SECONDS);
//                if (tryLock) {
//                    //上锁
//                    try {
//                        skuInfo = skuInfoMapper.selectById(skuId);
//                        if (null != skuInfo) {
//                            skuInfo.setSkuImageList(skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId)));
//                            //3.将结果添加到缓存
//                            redisTemplate.opsForValue().set(cacheKey, skuInfo,
//                                    //为避免缓存雪崩 原有的失效时间基础上增加一个随机值
//                                    RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300),
//                                    TimeUnit.SECONDS);
//                        } else {
//                            //如果数据库也没有 为避免缓存穿透
//                            skuInfo = new SkuInfo();//空结果 空对象
//                            redisTemplate.opsForValue().set(cacheKey, skuInfo, 5, TimeUnit.MINUTES);
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }finally {
//                        //解锁
//                        lock.unlock();
//                    }
//                } else {
//                    //为避免获得锁的线程未查询完 先睡一会儿再查 不过我认为不好
//                    TimeUnit.SECONDS.sleep(2);
//                    //没有上锁 就代表其他线程获取到了锁 那就去查缓存
//                    skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
//                }
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
//        //4.返回结果
//        return skuInfo;
//    }

    //2: 一二三级分类 ID名称 通过视图简化查询
    @Override
    @GmallCache(prefix = "getBaseCategoryView")
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    //3: 单独查询实时价格 实时价格绝对不能加到缓存中
    @Override
    public BigDecimal getPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (null != skuInfo) {
            return skuInfo.getPrice();
        }
        return null;
    }

    //4: 查询销售属性及选中
    @Override
    @GmallCache(prefix = "List<SpuSaleAttr>")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long spuId, Long skuId) {
        List<SpuSaleAttr> spuSaleAttrListCheckBySku = spuSaleAttrMapper.getSpuSaleAttrListCheckBySku(spuId, skuId);
        return spuSaleAttrListCheckBySku;
    }

    //5: 查询组合对应的SKUID 为了销售属性选择 跳转 刷新功能
    @Override
    @GmallCache(prefix = "getSkuValueIdsMap")
    public Map getSkuValueIdsMap(Long spuId) {
        List<Map> skuValueIdsMap = skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        HashMap map = new HashMap<>();
        skuValueIdsMap.forEach(m -> {
            map.put(m.get("values_id"), m.get("sku_id"));
        });
        return map;
    }

    //6: 查询所有分类视图 集合
    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }

    //7: 根据ID获取品牌
    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }

    //8: 查询某一款商品的平台属性集合
    @Override
    public List<SkuAttrValue> getSkuAttrValueAndAttrAndAttrValue(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValueAndAttrAndAttrValue(skuId);
    }
}
